<template>
  <div class="register">
    <el-card :xl="6" :md="8" :sm="12" :xs="22" class="box-card card">
      <p class="login-welcome">&nbsp;&nbsp;欢迎注册！</p>
      <div style="margin-top: 10px"></div>
      <el-avatar :src="changeimg" style="cursor: pointer" title="点击修改图片" @click.native.prevent="getimg"></el-avatar>
      <input type="file" id="imgup" ref="inputer" accept="image/*" @change="upload_photo"
             style="display: none;"/>
      <div style="margin-top: 10px"></div>

      <el-form :model="form" :rules="rules" ref="register">
        <el-form-item label="昵称" :label-width="formLabelWidth" prop="userName">
          <el-input v-model="form.userName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
          <el-input v-model="form.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
          <el-input v-model="form.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="code" label="验证码" :label-width="formLabelWidthcode">
          <div id="code" style="display: flex;flex-direction: row;justify-content: center;align-items: center">
            <el-input
                placeholder="验证码"
                v-model="form.code"
                onkeyup="this.value=this.value.replace(/[^\d.]/g,'');"
                maxlength="6"
            >
            </el-input>
            <el-button type="primary" style="border-radius: 0 5px 5px 0" @click.native.prevent="SendCode"
                       :disabled="disabled=!show">
              <span v-show="show">验证码</span>
              <span v-show="!show" class="count">{{ count }} s</span>
            </el-button>
          </div>
        </el-form-item>
        <el-form-item>
          <el-radio v-model="radio" label="1">用户</el-radio>
          <el-radio v-model="radio" label="2">专家</el-radio>
        </el-form-item>

        <el-upload class="upload" v-if="radio!=1" action="#" list-type="picture-card" :auto-upload="false" ref="upload"
                   :limit="limit"
                   :on-exceed="moreout" :on-change="handleChange" :multiple="true"
                   style="height: 148px;border: 1px dashed #eaeaea;padding: 5px;margin-top: 10px;margin-bottom: 20px">
          <i slot="default" class="el-icon-plus"></i>
          <div slot="file" slot-scope="{file}">
            <img class="el-upload-list__item-thumbnail" :src="file.url" alt=""/>
            <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                <i class="el-icon-zoom-in"></i>
                </span>
                <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                  <i class="el-icon-delete"></i>
                </span>
             </span>
          </div>
        </el-upload>

        <el-button type="primary" style="width: 290px" @click="changw">注册</el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "Register",
  data() {
    return {
      loading: false,
      limit: 2,
      disabled: false,
      restaurants: [],
      changeimg: require("../assets/icon-注册头像.png"),
      formData: null,
      formLabelWidth: '70px',
      formLabelWidthcode: '70px',
      show: true,  // 初始启用按钮
      count: '',   // 初始化次数
      form: {
        userName: "",
        phone: "",
        password: "",
        code: ""
      },
      rules: {
        phone: [{required: true, message: '请输入手机号', trigger: 'blur'}],
        code: [{required: true, message: '请输入验证码', trigger: 'blur'}],
        userName: [{required: true, message: '请输入昵称', trigger: 'blur'}],
        password: [{required: true, message: '请输入昵称', trigger: 'blur'}],
      },
      radio: "1",
      param: null,
      filearr: [],
    };
  },
  methods: {
    authentication() {
      if (this.filearr.length == 0) {
        this.$message.error("请上传认证")
        return
      }
      this.param = new FormData()
      this.filearr.forEach((file) => {
        this.param.append(`file`, file) // 把单个文件重命名，存储起来（给后台）
      })
      return new Promise(resolve => {
        this.$http({
          method: "post",
          url: "/doctor/insertDoctorImg",
          headers: {
            'Content-Type': 'multipart/form-data',
          },
          data: this.param
        }).then(data => {
          resolve(data.data)
        })
      })
    },
    handleChange(file) {
      const fileObj = file.raw;
      if (file && fileObj) {
        this.filearr.push(fileObj)
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
    },
    moreout() {
      this.$message.warning("最多上传两张照片！")
    },
    handleRemove(file) {
      let fileList = this.$refs.upload.uploadFiles;
      let index = fileList.findIndex(fileItem => {
        return fileItem.uid === file.uid
      });
      fileList.splice(index, 1);

      let aList = this.filearr
      let aIndex = aList.findIndex(fileItem => {
        return fileItem.uid === file.uid
      });
      this.filearr.splice(aIndex, 1)
    },
    SendCode() {
      if (this.form.phone == "") {
        this.$message.error("请输入手机号码")
        return
      }
      if (!this.phoneFun(this.form.phone)) {
        this.$message.error("请输入正确手机号！！")
        return
      }
      this.isSendCode = true;
      const TIME_COUNT = 60;
      if (!this.timer) {
        this.count = TIME_COUNT;
        this.show = false;
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--;
          } else {
            this.show = true;
            clearInterval(this.timer);  // 清除定时器
            this.timer = null;
          }
        }, 1000)
      }
      let data = {
        phone: this.form.phone
      }
      console.log(data)
      this.$http.post(
          '/login/loginwithcode',
          data
      ).then(data => {
        console.log(data)
      })
    },
    async changw() {
      if (this.radio == '2') {
        if (this.filearr.length == 0) {
          this.$message.error("请上传认证")
          return
        }
      }
      if (this.form.phone == "" || this.form.userName == "" || this.form.password == "") {
        this.$message.error("请输入全部信息！！")
        return
      }
      if (!this.phoneFun(this.form.phone)) {
        this.$message.error("请输入正确手机号！！")
        return
      }
      if (this.formData == null) {
        this.$message.error("请设置头像！！")
        return
      }
      this.$http({
        method: "post",
        url: "/login/uploadImg",
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        data: this.formData
      }).then(data => {
        //console.log(data)
        if (data.code == 200) {
          this.login(data.data)
        }
      })
    },
    upload_photo() {
      const file = document.getElementById('imgup');
      const fileObj = file.files[0];
      const windowURL = window.URL || window.webkitURL;
      if (file && fileObj) {
        const dataURl = windowURL.createObjectURL(fileObj);
        this.changeimg = dataURl;
        let formData = new FormData();
        formData.append('file', fileObj);
        this.formData = formData;
      }
    },
    getimg() {
      document.getElementById("imgup").click();
    },
    phoneFun(phones) {
      var myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
      if (!myreg.test(phones)) {
        return false;
      } else {
        return true;
      }
    },
    login(logo) {
      if (this.form.phone == "" || this.form.userName == "" || this.form.password == "") {
        this.$message.error("请输入全部信息！！")
        return
      }
      if (!this.phoneFun(this.form.phone)) {
        this.$message.error("请输入正确手机号！！")
        return
      }
      if (this.formData == null) {
        this.$message.error("请设置头像！！")
        return
      }
      this.form.logo = logo

      if (this.radio == '2') {
        this.authentication().then(res => {
          console.log(res)
          let idsarr = []
          if (res != "") {
            for (let i = 0; i < res.length; i++) {
              idsarr.push(res[i].id)
            }
          }
          this.form.imgId = idsarr
          console.log(this.form)
          this.$http.post("/doctor/uploadDoctor", this.form)
        })
        this.$http.post("/login/register", this.form).then(async data => {
          if (data.code == 400) {
            this.$message.error(data.message)
            this.changeimg = require("../assets/icon-注册头像.png")
          } else {
            this.$message.success("注册成功！请等待管理员审核")
            this.$router.push("/")
          }
        })
      } else {
        this.$http.post("/login/register", this.form).then(async data => {
          if (data.code == 400) {
            this.$message.error(data.message)
            this.changeimg = require("../assets/icon-注册头像.png")
          } else {
            this.$message.success("注册成功！")
            this.$router.push("/")
          }
        })
      }
    },
    querySearch(queryString, callback) {
      let restaurants = this.restaurants;
      let results = JSON.parse(JSON.stringify(restaurants)); //把数组的浅复制换成深复制
      for (let item in results) {
        results[item].value =
            queryString.split("@")[0] + "" + restaurants[item].value;
      }
      callback(results);
    },
    loadAll() {
      return [
        {value: "@qq.com"},
        {value: "@126.com"},
        {value: "@163.com"},
        {value: "@sohu.com"},
      ];
    },
  },
  mounted() {
    this.restaurants = this.loadAll();
  },
}
</script>

<style scoped>
#code >>> el-input >>> input {
  border-radius: 5px 0 0 5px !important;
}

.upload /deep/ .el-upload {
  float: right;
}

.register {
  height: 100vh;
  background: linear-gradient(
      270deg, rgb(219, 223, 229), rgba(125, 227, 133, 0.5), rgba(220, 67, 126, 0.5));
}

.card {
  width: 520px;
  /*height: 350px;*/
  position: absolute;
  padding: 5px 10px 5px 10px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

p {
  text-align: center;
  color: #51cacc;
  line-height: 30px;
  margin-bottom: 10px;
  font-weight: 700;
  letter-spacing: 3px;
  margin-top: 15px;
}

.btn {
  width: 60%;
  height: 40px;
  background-image: linear-gradient(
      270deg, rgba(142, 239, 252, .9), rgba(142, 197, 252, .6));
  color: #fff;
  margin: 20px 0;
}
</style>